<template>
  <div class="wrapper">
    <el-card>
      <div class="list">
        <div class="item">
          <div class="item_title"><span class="required"></span>选择变更节点</div>
          <div class="node_wrapper">
            <div class="nodes" style="overflow-x: auto;width: 58VW">
              <stepBox
                v-for="(item, index) of nodes"
                :id="item.proNodeId"
                :key="item.proNodeId"
                :active="item.proNodeId !== periodId"
                :inputValue="item.nodeName"
                :currentIndex="index"
                @handleClose="togglePeriod">
              </stepBox>
            </div>
            <el-button v-if="nodeIsAudit" class="changes" type="text" @click="enterDetail">变更审批中</el-button>
          </div>
        </div>
        <div class="item">
          <div class="item_title"><span class="required"></span>项目周期</div>
          <div class="time">
            <el-date-picker
              v-model="proStartDate"
              type="date"
              placeholder="选择日期"
              :clearable="false"
              :disabled="isExpired || canEdit"
              :picker-options="pickerProjectStartOptions"
              @change="value => dateChanges(value, 'proStartDate')"
            />
            &nbsp;&nbsp;-&nbsp;&nbsp;
            <el-date-picker
              v-model="proEndDate"
              type="date"
              placeholder="选择日期"
              :disabled="isExpired || canEdit"
              :clearable="false"
              :picker-options="pickerProjectEndOptions"
              @change="value => dateChanges(value, 'proEndDate')"
            />
          </div>
        </div>
        <div class="item">
          <div class="item_title"><span class="required"></span>节点周期</div>
          <div class="time">
            <el-date-picker
              v-model="nodeStartDate"
              type="date"
              placeholder="选择日期"
              :clearable="false"
              :disabled="isExpired || canEdit"
              :picker-options="pickerNodeStartOptions"
              @change="value => dateChanges(value, 'nodeStartDate')"
            />
            &nbsp;&nbsp;-&nbsp;&nbsp;
            <el-date-picker
              v-model="nodeEndDate"
              type="date"
              placeholder="选择日期"
              :clearable="false"
              :disabled="isExpired || canEdit"
              :picker-options="pickerNodeEndOptions"
              @change="value => dateChanges(value, 'nodeEndDate')"
            />
          </div>
        </div>
        <div class="item_checkbox">
          <el-checkbox v-model="isLimit" :disabled="isExpired || canEdit " @change="toggleLimit">剔除节假日</el-checkbox>
        </div>
        <div class="item">
          <div class="item_title" />
          <div class="time time_table">
            <el-table :disabled="isExpired" border :data="dataSource" :header-cell-style="tableHeaderStyle">
              <el-table-column
                prop="proroleName"
                label="角色"
                align="center"
                fixed="left"
                width="100"
              />
              <el-table-column
                prop="userName"
                label="成员"
                align="center"
                fixed="left"
                width="100"
              />
              <el-table-column
                label="投入方式"
                prop="way"
                width="110"
                align="center"
                fixed="left"
              >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.inputType" :disabled="isExpired || canEdit" placeholder="请选择" @change="value => selectChanges(value, scope)">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="开始"
                prop="way"
                width="150"
                align="center"
                fixed="left"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.inputStart"
                    class="datePicker"
                    type="date"
                    placeholder="选择日期"
                    :disabled="isExpired || canEdit "
                    :clearable="false"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions_start[`${scope.$index}`]"
                    style="width: 120px"
                    @change="value => dateChanges(value, 'startDate', scope, scope.$index)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="结束"
                prop="way"
                width="150"
                align="center"
                fixed="left"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    v-model="scope.row.inputEnd"
                    class="datePicker"
                    :clearable="false"
                    placeholder="选择日期"
                    :picker-options="pickerOptions_end[`${scope.$index}`]"
                    :disabled="isExpired || canEdit"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    style="width: 120px"
                    @change="value => dateChanges(value, 'endDate', scope, scope.$index)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="累计投入"
                prop="total"
                width="100"
                align="center"
                fixed="left"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.inputHours" class="workhour" type="number" :disabled="scope.row.inputType == 1 || isExpired || canEdit" placeholder="" @change="value => inputTotalChanges(value, scope)" />
                </template>
              </el-table-column>
              <el-table-column v-for="item of columns" :key="item.id" :prop="item.prop" :label="item.label && item.label.replace(/-/g, '.')" width="100" align="center">
                <template slot-scope="scope">
                  <el-input v-if="isShow(scope.row, item.label)" v-model="scope.row[`${item.label}`]" class="workhour" type="number" :disabled="isExpired || canEdit || isReady(scope, item.label)" placeholder="" @change="value => inputChanges(value, scope.row, scope.$index, item.label)" />
                </template>
              </el-table-column>
            </el-table>
            <el-button class="addUser" :disabled="isExpired || nodeIsAudit || !currentNodeIsAssgin || canEdit " :type="isExpired || nodeIsAudit || !currentNodeIsAssgin || canEdit ?'info':'primary'" icon="el-icon-add" @click="addUser">添加人员</el-button>
          </div>
        </div>
        <div class="item">
          <div class="item_title item_summary"><span class="required"></span>修改概要</div>
          <div class="summary">
            <el-input
              v-model.trim="summary"
              :disabled="isExpired || canEdit"
              type="textarea"
              :rows="4"
              placeholder=""
              :maxlength="500"
            />
          </div>
        </div>
      </div>
      <div class="operation">
        <el-button :disabled="isExpired || canEdit" @click="reset">还原</el-button>
        <el-button :class="nodeIsAudit ? 'tips': isExpired ? 'tips2': (!currentNodeIsAssgin && currentProNodeIndex) ? 'tips3': boo ? 'tips4':''" :type="isExpired || nodeIsAudit || !currentNodeIsAssgin || canEdit || submitFlag ? 'info': 'primary'" :disabled="isExpired || nodeIsAudit || !currentNodeIsAssgin || canEdit || submitFlag"  @click="enterUsed">提交</el-button>
      </div>
      <userList ref="userList" :select-show="true" :is-show-search="false" :choseList="dataSource" @handleChose="closeDialog" />
      <el-dialog
        title="是否提交当前页面数据？"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose"
      >
        <span style="color: red">选择确定将给主管发送钉钉审批</span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveData">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import userList from '@/components/userList'
import moment from 'moment'
import { http_project_Detail, http_project_update, http_workDay, http_saveDING } from '@/api/projectChanges'
import {tableHeaderStyle} from '@/utils/constant'
import stepBox from '@/components/StepBox/index'
import {Message} from "element-ui";

export default {
  components: {
    userList,
    stepBox
  },
  data() {
    return {
      timesFalg: this.isExpired || this.canEdit,
      nodes: [],
      proStartDate: '',
      proEndDate: '',
      nodeStartDate: '',
      nodeEndDate: '',
      summary: '',
      addMemberVisible: false,
      periodId: 0,
      dataSource: [],
      initDataSource: [], // 未修改之前的数据
      columns: [],
      options: [
        {
          label: '自定义',
          value: 1
        },
        {
          label: '平均',
          value: 2
        }
      ],
      endDate: '',
      startDate: '',
      id: null,
      isAddUser: false, // 是否是新增人员
      isPersonnelChanges: false, // 是否是人员变更
      detailInfo: {}, // 默认值
      nodeDateRangeDays: [],
      isLimit: false,
      workDays: [], // 两个日期差之间的工作日期(包括节假期、周六、周末)
      dialogVisible: false,
      currentClickNodeId: '',
      periodStatusChanges: [false, false, false, false], // 是否是周期变化 分别代表项目开始周期、项目结束周期、节点开始周期、节点结束周期是否发生变化
      tableHeaderStyle,
      isExpired: false,
      pickerOptions_start:{},
      pickerOptions_end:{},
      currentProNodeIndex: null,
      switchProNodeChangeStartTime: null,
      switchProNodeChangeEndTime: null,
      switchProChangeStartTime:null,
      switchProChangeEndTime:null,
      submitFlag:false,
      serverDate: ''
    }
  },
  watch:{
      proStartDate: function(proStartDate,oldProStartDate){
          if (this.nodeStartDate != null && new Date(this.nodeStartDate) < new Date(proStartDate)) this.nodeStartDate = null
          if (this.nodeEndDate != null && new Date(this.nodeEndDate) < new Date(proStartDate)) this.nodeEndDate = null

          // 项目 结束周期往前调报错
          if(this.switchProChangeStartTime == null){
              let minNodeStartDate = this.nodes[0].startDate
              if(new Date(new Date(proStartDate).toLocaleDateString()).getTime()> new Date(new Date(minNodeStartDate).toLocaleDateString()).getTime()){
                  Message.error('项目的开始日期，不能大于第一个节点的开始日期')
                  this.proStartDate = oldProStartDate
              }
          }

          // 处理节点变化导致 周期变化
          if(this.switchProChangeStartTime != null){
              this.switchProChangeStartTime = null
          }
      },
      proEndDate: function(proEndDate,oldProEndDate){
          if (this.nodeStartDate != null && new Date(this.nodeStartDate) > new Date(proEndDate)) this.nodeStartDate = null
          if (this.nodeEndDate != null && !moment(this.nodeEndDate).isSameOrBefore(moment(proEndDate))) this.nodeEndDate = null

          // 项目 结束周期往前调报错
          if(this.switchProChangeEndTime == null){
              let maxNodeEndDate = this.nodes[this.nodes.length-1].endDate
              if(new Date(new Date(proEndDate).toLocaleDateString()).getTime()< new Date(new Date(maxNodeEndDate).toLocaleDateString()).getTime()){
                  Message.error('项目的结束日期，不能小于最后一个节点的结束日期')
                  this.proEndDate = oldProEndDate
              }
          }
          // 处理节点变化导致 周期变化
          if(this.switchProChangeEndTime != null){
              this.switchProChangeEndTime = null
          }
      },
      nodeStartDate: function(nodeStartDate,oldNodeStartDate){
          if (this.dataSource != null && this.dataSource.length){
              this.dataSource.forEach((d,i)=>{
                  if (d.inputStart != null && new Date(d.inputStart) < new Date(nodeStartDate)) d.inputStart = null
                  if (d.inputEnd != null && new Date(d.inputEnd) < new Date(nodeStartDate)) d.inputEnd = null
              })
          }

          // 节点 开始周期往前调报错
          if (this.switchProNodeChangeStartTime == null && this.currentProNodeIndex >0){
              let endDate = this.nodes[this.currentProNodeIndex-1].endDate
              if(nodeStartDate != null && new Date(new Date(nodeStartDate).toLocaleDateString()).getTime()<= new Date(new Date(endDate).toLocaleDateString()).getTime()){
                  Message.error('本节点的开始日期，不能小于前一个节点的结束日期')
                  this.nodeStartDate = oldNodeStartDate
              }
          }
          // 处理节点变化导致 周期变化
          if(this.switchProNodeChangeStartTime != null){
              this.switchProNodeChangeStartTime = null
          }

      },
      nodeEndDate: function(nodeEndDate,oldNodeEndDate){
          if (this.dataSource != null && this.dataSource.length){
              this.dataSource.forEach((d,i)=>{
                  if (d.inputStart != null && new Date(d.inputStart) > new Date(nodeEndDate)) d.inputStart = null
                  if (d.inputEnd != null && new Date(d.inputEnd) > new Date(nodeEndDate)) d.inputEnd = null
              })
          }
          // 节点周期往后调报错
          if ( this.switchProNodeChangeEndTime == null && this.currentProNodeIndex < this.nodes.length-1){
              let startDate = this.nodes[this.currentProNodeIndex+1].startDate
              if(nodeEndDate != null && new Date(new Date(nodeEndDate).toLocaleDateString()).getTime()>= new Date(new Date(startDate).toLocaleDateString()).getTime()){
                  Message.error('本节点的结束日期，不能大于后一个节点的开始日期')
                  this.nodeEndDate = oldNodeEndDate
              }
          }
          // 处理节点变化导致 周期变化
          if(this.switchProNodeChangeEndTime != null){
            this.switchProNodeChangeEndTime = null
          }

      },
      currentProNodeIndex: function (currentProNodeIndex,oldCurrentProNodeIndex){
          this.switchProNodeChangeStartTime = Date.now()
          this.switchProNodeChangeEndTime = Date.now()
          // this.switchProChangeStartTime = Date.now()
          // this.switchProChangeEndTime = Date.now()
      },
      'dataSource':{
          handler(dataSource,oldDataSource){
              // 日期禁用部分
              let start = this.getMaxTime( [this.proStartDate,this.nodeStartDate])
              let end = this.getMinTime( [this.proEndDate,this.nodeEndDate])
              dataSource.forEach((d,i)=>{
                  const s = 24 * 60 * 60 * 1000;
                  let start1 = this.getMaxTime( [this.proStartDate,this.nodeStartDate,d.inputStart])
                  let end1 = this.getMinTime( [this.proEndDate,this.nodeEndDate,d.inputEnd])
                  this.pickerOptions_start[`${i}`]={
                      disabledDate(time) {
                          return time.getTime() < Date.now() - s || time.getTime() < start ||  time.getTime() > end1
                      }
                  }
                  this.pickerOptions_end[`${i}`]={
                      disabledDate(time) {
                          return time.getTime() < Date.now() - s || time.getTime() < start1 ||  time.getTime() > end
                      }
                  }
              })

              // 限制 每日人天为2
              dataSource.forEach((item,i)=>{
                  // 平均
                  if (item.inputType == 2){
                      this.workDays.forEach(workDay=>{
                          if (item[`${workDay.date}`]> 2 ){
                              Message.closeAll()
                              Message.warning('每日人天不能大于2')
                              item[`${workDay.date}`] = 0.00
                              item.inputHours = 0.00
                          }else {
                              item[`${workDay.date}`] = Number(item[`${workDay.date}`]).toFixed(2)
                              item.inputHours = this.getNumberTwo(item.inputHours)
                          }
                      })
                  }else { //自定义
                      this.workDays.forEach(workDay=>{
                          if (item[`${workDay.date}`]> 2 ){
                              Message.closeAll()
                              Message.warning('每日人天不能大于2')
                              item[`${workDay.date}`] = 0.00
                          }else {
                              // console.log(workDay.date,item[`${workDay.date}`])
                                if (item[`${workDay.date}`] != null){
                                    item[`${workDay.date}`] = this.getNumberTwo(item[`${workDay.date}`])
                                }
                              // item[`${workDay.date}`] = item[`${workDay.date}`] ? this.getNumberTwo(item[`${workDay.date}`]) : item[`${workDay.date}`]
                              item.inputHours = item.inputHours ? this.getNumberTwo(item.inputHours) : item.inputHours
                          }
                      })
                  }


              })

              // 解决某个bug
              dataSource.forEach(ds=>{
                  ds.roleId = ds.userId
                  ds.jueSe = Number(ds.proroleId || ds.selectValue )
              })
          },
          deep: true
      }


  },
  computed: {
    pickerProjectStartOptions: function() {
        const s = 24 * 60 * 60 * 1000;
        let end = this.getMinTime([this.proEndDate])
        return {
            disabledDate(time) {
                return time.getTime() < Date.now() - s ||  time.getTime() > end
            }
        }
    },
    pickerProjectEndOptions: function() {
        const s = 24 * 60 * 60 * 1000;
        let start = this.getMaxTime([this.proStartDate])
        return {
            disabledDate(time) {
                return time.getTime() < Date.now() - s || time.getTime() < start
            }
        }
    },
    pickerNodeStartOptions: function() {
        const s = 24 * 60 * 60 * 1000;
        let start = this.getMaxTime([this.proStartDate])
        let end = this.getMinTime([this.proEndDate,this.nodeEndDate])
        return {
            disabledDate(time) {
                return time.getTime() < Date.now() - s || time.getTime() < start || time.getTime() > end
            }
      }
    },
    pickerNodeEndOptions: function() {
        const s = 24 * 60 * 60 * 1000;
        let start = this.getMaxTime( [this.proStartDate,this.nodeStartDate])
        let end = this.getMinTime([this.proEndDate])
        return {
            disabledDate(time) {
                return time.getTime() < Date.now() - s || time.getTime() < start || time.getTime() > end
            }
        }
    },
    pickerOptions: function() {
      const _this = this
      return {
        disabledDate(time) {
          const start = new Date(_this.nodeStartDate)
          const end = new Date(_this.nodeEndDate)
          return time.getTime() < (start.getTime() - 24 * 3600 * 1000) || time.getTime() >= end.getTime()
        }
      }
    },
    endPickerOptions: function() {
      const _this = this
      return {
        disabledDate(time) {
          const end = new Date(_this.nodeEndDate)
          return time.getTime() > end.getTime()
        }
      }
    },
    /**
     * 当前节点是否审批包含两种情况， 一种是当前节点发起变更，未审批， 一种是审批完成之后，不在proChangebaseList里面
     */
    nodeIsAudit: function() {
      const flag = (this.detailInfo && this.detailInfo.proChangebaseList && this.detailInfo.proChangebaseList.some(item => item.proNodeId === this.periodId)) || false
      return flag
    },
    isShow: function() {
      return function(item, date) {
        return item.inputStart && item.inputEnd && item.inputType && moment(date).isBetween(item.inputStart, item.inputEnd, null, '[]')
      }
    },
    currentNodeIsAssgin: function() {
      const changesArr = this.detailInfo && this.detailInfo.proAssignmentList && this.detailInfo.proAssignmentList.filter(item => item.nodeId == this.periodId && item.inputHours)
      return changesArr && changesArr.length > 0
    },
    boo: function (){
        return  new Date().toLocaleDateString > new Date(this.nodeEndDate).toLocaleDateString;
    },
    canEdit:function (){
        const flag = (this.detailInfo && this.detailInfo.proChangebaseList && this.detailInfo.proChangebaseList.length>0) || false
        return flag
    },
    periodChange:function (){
        return {
                currentProNodeIndex:this.currentProNodeIndex,
                nodeStartDate:this.nodeStartDate,
                nodeEndDate:this.nodeEndDate,
                proStartDate:this.proStartDate,
                proEndDate:this.proEndDate
        }
    },
    isBeforeSystemDate: function(){
      return function(item) {
        return item.label && this.serverDate && moment(item.label).isBefore(this.serverDate) || false
      }
    }

  },
  mounted() {
    this.init()
  },
  methods: {
      getNumberTwo(num){
          return Number(num.toString().match(/^\d+(?:\.\d{0,2})?/));
      },
      isReady(scope, date) {
        const row = scope.row
        if (row.inputType == 2) {
          // if (date && row.inputStart && row.inputEnd) {
          //   return !moment(date).isBetween(row.inputStart, row.inputEnd, null, '[]')
          // }
          return true
        } else {
          if (date && row.inputStart && row.inputEnd) {
            return !moment(date).isBetween(row.inputStart, row.inputEnd, null, '[]')
          }
        }
        return true
      },
      getMaxTime(params){
          let times = params.filter((s)=>{if(s != null && s != '' ) return s })
          return new Date(new Date(new Date(Math.max.apply(null,times.map((e=>new Date(e))))).getTime()).toLocaleDateString())
      },
      getMinTime(params){
          let times = params.filter((s)=>{if(s != null && s != '' ) return s })
          return new Date(new Date(new Date(Math.min.apply(null,times.map((e=>new Date(e))))).getTime()).toLocaleDateString())
      },
    init() {
      this.id = this.$route.query.id
      // this.id = 75
      this.$nextTick(() => {
        this.getProjectInfo()
      })
    },
     getMax(...param){

     },
    togglePeriod(proNodeId, index) {
          // console.log(index)
      const targetIndex = this.detailInfo.proNodeList.findIndex(item => item.current)
      if (this.periodId == proNodeId) return
      if (index < targetIndex) {
        this.isExpired = true
        this.$message('当前节点已过期,无法提交变更')
          this.currentProNodeIndex = index
      } else if(index > targetIndex) {
        const currentNodeIsChange =  this.detailInfo.proAssignmentList.filter(item => item.nodeId == proNodeId && item.inputHours).length === 0
        if (currentNodeIsChange) {
          // console.log(currentNodeIsChange)
          this.$message('当前节点未分配,无法提交变更')
          this.isExpired = false
          return
        }
        this.isExpired = false
        this.currentProNodeIndex = index
      } else {
        this.isExpired = false
        this.currentProNodeIndex = index
      }
      const isChange = this.checkCurrentNodeIsChanges()
      if (this.nodeIsAudit || !isChange) {
        this.periodId = proNodeId
        this.$nextTick(() => {
          this.setDefaultValue()
        })
      } else {
        this.dialogVisible = true
        this.currentClickNodeId = proNodeId
      }
    },
    addUser() {
      this.$refs.userList.centerDialogVisible2 = true
    },
    // 查询项目详细信息
    getProjectInfo() {
      const params = {
        id: this.id
      }
      http_project_Detail(params).then(res => {
        const { stateCode, data } = res
        if (stateCode === '0000') {
          this.submitFlag = false
          this.nodes = data.proNodeList || []
          this.serverDate = data.serverDate
          let currentNodeId = ''
          this.detailInfo = data
          const changesItemCache = sessionStorage.getItem('changesItem')
          if (!changesItemCache && Array.isArray(data.proNodeList)) {
            let currentNode = data.proNodeList.filter(item => item.current) || []
            if (currentNode == null || currentNode.length == 0){
                currentNode.push(data.proNodeList[0])
            }
            currentNodeId = currentNode && currentNode[0].proNodeId
            this.currentProNodeIndex = data.proNodeList.findIndex(item=> item.proNodeId == currentNodeId) || 0
              console.log(this.currentProNodeIndex)
            this.periodId = currentNodeId || (data[0] && data[0].proNodeId)
          } else {
            this.periodId = changesItemCache
            sessionStorage.setItem('changesItem', '')
          }
          this.$nextTick(() => {
            this.setDefaultValue()
          })
        }
      })
    },
    /**
     * 设置不同的默认值
     */
    async setDefaultValue() {
      // console.log('dataSource', this.detailInfo.proAssignmentList && this.detailInfo.proAssignmentList.filter(item => item.nodeId == this.periodId) || [])
      this.isLimit = false
      const nodeStartDate = this.detailInfo.proNodeList.filter(item => item.proNodeId === this.periodId)[0].startDate
      const nodeEndDate = this.detailInfo.proNodeList.filter(item => item.proNodeId === this.periodId)[0].endDate
      this.proStartDate = this.detailInfo.proStartDay
      this.proEndDate = this.detailInfo.proEndday
      this.nodeStartDate = nodeStartDate
      this.nodeEndDate = nodeEndDate
      this.dataSource = this.detailInfo.proAssignmentList && this.detailInfo.proAssignmentList.filter(item => item.nodeId == this.periodId) || []
      this.initDataSource = this.detailInfo.proAssignmentList && this.detailInfo.proAssignmentList.filter(item => item.nodeId == this.periodId) || []
      this.summary = ''
      this.periodStatusChanges = [false, false, false, false]
      if (nodeStartDate && nodeEndDate) {
        const dates = await this.getAll(nodeStartDate, nodeEndDate)
        this.generateColumns(dates, true)
      }
    },
    /**
     * 选中项
     */
    selectedItem(item) {
      this.addMemberVisible = false
      this.isPersonnelChanges = true
    },
    /**
     * begin 格式为2020-9-20
     * end   格式为2020-9-20
     */
    async getAll(begin, end) {
      const params = {
        beginDate: begin,
        endDate: end
      }
      const res = await http_workDay(params)
      const datas = []
      res.data.map(item => datas.push({
        date: Object.keys(item)[0],
        isValid: Object.values(item)[0]
      }))
      this.workDays = datas
      if (!this.isLimit) {
        return datas.map(el => el.date)
      } else {
        return datas.filter(item => item.isValid).map(el => el.date)
      }
    },
    async enterUsed() {
      const isValidate = this.checkDataIsVilidate()
      if (!isValidate) return false
      const preTotalDay = this.initDataSource.reduce((total, curr) => total += Number((curr.inputHours || 0)), 0)
      const params = {
        proId: this.id || this.detailInfo.id,
        proNodeId: this.periodId,
        oldProStartDate: this.detailInfo.proStartDay,
        oldProEndDate: this.detailInfo.proEndday,
        newProStartDate: this.proStartDate && moment(this.proStartDate).format('YYYY-MM-DD'),
        newProEndDate: this.proEndDate && moment(this.proEndDate).format('YYYY-MM-DD'),
        oldNodeStartDate: this.detailInfo.proNodeList.filter(item => item.proNodeId === this.periodId)[0].startDate,
        oldNodeEndDate: this.detailInfo.proNodeList.filter(item => item.proNodeId === this.periodId)[0].endDate,
        newNodeStartDate: this.nodeStartDate && moment(this.nodeStartDate).format('YYYY-MM-DD'),
        newNodeEndDate: this.nodeEndDate && moment(this.nodeEndDate).format('YYYY-MM-DD'),
        changeSummary: this.summary,
        inputHourOld: preTotalDay,
        inputHourNew: this.dataSource.reduce((total, curr) => total += Number((curr.inputHours || 0)), 0)
      }
      params.updateUserTOList = this.getPersonChangesArr() || []
      const addUserTOList = []
      const addUserList = this.dataSource.filter(item => item.hasOwnProperty('isAdd'))
      addUserList.map(item => {
        const arr = []
        this.columns.filter(el => item[`${el.label}`]).map(curr => arr.push({
          userId: item.userId,
          inputHours: item[`${curr.label}`],
          changeDate: curr.label
        }))
        addUserTOList.push({
          userName: item.userName,
          userId: item.userId,
          proChangeHours: arr,
          inputType: item.inputType,
          inputTypeName: this.options.filter(el => item.inputType == el.value)[0].label,
          inputStart: item.inputStart,
          inputEnd: item.inputEnd,
          inputDaily: item.inputHours,
          proRoleId: item.proRoleId
        })
      })
      params.addUserTOList = addUserTOList || []
        // console.log("params",params)

      if (!params.changeSummary.trim()) {
        this.$message('请输入修改概要')
        return false
      }
      this.submitFlag = true
      const res = await http_project_update(params)
      const { stateCode, message, data } = res
      if (stateCode && stateCode === '0000') {
        const currentNode = this.nodes.filter(element => element.proNodeId === this.periodId)[0].nodeName
        const params2 = {
          ...params,
          changeNo: data,
          proName: this.detailInfo.proName,
          nodeName: currentNode

        }
        const response = await http_saveDING(params2)

        if (response.stateCode && response.stateCode === '0000') {
          this.$message({
            message: '提交成功',
            type: 'success'
          })
          this.getProjectInfo()
          return true
        } else {
          this.$message(response.message)
          return false
        }

      } else {
          this.$message(message)
        return false
      }

    },
    /**
     * 检查数据是否合法
     */
    checkDataIsVilidate() {
      const flag = true
      if (!this.proStartDate || !this.proEndDate) {
        this.$message('请填写项目周期')
        return !flag
      } else if (!this.nodeStartDate || !this.nodeEndDate) {
        this.$message('请填写节点周期')
        return !flag
      } else {
        // const isNuLL = this.dataSource.some(item => !item.inputHours || !item.inputStart || !item.inputEnd)
        // const isZero = this.dataSource.some(item => item.inputHours == 0)
        // const isValidate = this.dataSource.some(item => !moment(item.inputStart).isSameOrBefore(item.inputStart) || !moment(item.inputEnd).isBetween(item.inputStart, this.nodeEndDate, null, '[]'))
        if (!this.dataSource.length) {
          this.$message('请添加人员')
          return !flag
        }
        // else if (isZero) {
        //   this.$message('累计投入不能为0')
        //   return !flag
        // } else if (isNuLL) {
        //   this.$message('请补充表格数据')
        //   return !flag
        // } else if (isValidate) {
        //   this.$message('开始日期要小于结束日期且小于节点周期的结束日期')
        //   return !flag
        // }
        //   console.log('dataSource',this.dataSource)
          let m = 0
          this.dataSource.forEach(p=>{
              if (p.inputStart === null || p.inputEnd === null || p.inputHours === null || p.inputStart === '' || p.inputEnd === '' || p.inputHours === ''  ){
                  m++
              }
          })
          if (m>0){
              Message.error(" 每个成员: 开始 / 结束 / 累计投入，都不可为空")
              return  false;
          }



        return true
      }
    },
    /**
     * 获取人员变更数组
     */
    getPersonChangesArr() {
      const updateUserTOList = []
      const arr = this.dataSource.filter(item => !item.hasOwnProperty('isAdd'))
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        const isChange = item.changesArr.some(el => el)
        const preData = this.initDataSource[i]
        const currentValueDays = []
        const preValueDays = []
        this.columns.map(el => item[`${el.label}`] && Number(item[`${el.label}`]) && currentValueDays.push({
          day: el.label,
          value: item[`${el.label}`]
        }))
        preData.planHoursList.map(el => el.inputHours && Number(el.inputHours) && moment(el.planDate).isBetween(preData.inputStart, preData.inputEnd, null, '[]') && preValueDays.push({
          day: el.planDate,
          value: el.inputHours
        }))
        const isFlag = currentValueDays.length == preValueDays.length
        const isValueChanges = currentValueDays.length > 0 ? !(isFlag && (preValueDays.every(el => currentValueDays.some(curr => Number(curr.value) == Number(el.value) && curr.day == el.day)))) : false
        if (isChange || isValueChanges) {
          const lastDays = []
          currentValueDays.map(el => lastDays.push({
            userId: item.userId,
            inputHours: el.value,
            changeDate: el.day
          }))
          updateUserTOList.push({
            userName: item.userName,
            userId: item.userId,
            inputTypeOld: preData.inputType,
            inputTypeNew: item.inputType,
            inputTypeNameOld: this.options.filter(el => preData.inputType == el.value)[0].label,
            inputTypeNameNew: this.options.filter(el => item.inputType == el.value)[0].label,
            inputStartNew: item.inputStart && moment(item.inputStart).format('YYYY-MM-DD'),
            inputEndNew: item.inputEnd && moment(item.inputEnd).format('YYYY-MM-DD') ,
            inputStartOld: preData.inputStart,
            inputEndOld: preData.inputEnd,
            inputDailyOld: preData.inputHours,
            inputDailyNew: item.inputHours,
            proChangeHours: lastDays,
            proroleId: item.proroleId
          })
        }
      }
      return updateUserTOList
    },
    // 判断当前节点数据是否发生变更
    checkCurrentNodeIsChanges() {
      const dateIsChange = this.periodStatusChanges.some(item => item)
      const updatesArr = this.getPersonChangesArr() || []
      const isUpdate = this.dataSource.length > 0 && updatesArr && updatesArr.length !== 0
      const isAdd = this.dataSource.some(item => item.hasOwnProperty('isAdd'))
      if (dateIsChange || isUpdate || isAdd) {
        return true
      } else {
        return false
      }
    },
    // 日期变化
    async dateChanges(value, str, scope, index) {

      if (str === 'nodeStartDate') {
        if (this.nodeEndDate && value) {
          const dates = await this.getAll(moment(value).format('YYYY-MM-DD'), moment(this.nodeEndDate).format('YYYY-MM-DD'))
          this.generateColumns(dates)
          const preStart = this.detailInfo.proNodeList.filter(item => item.proNodeId === this.periodId)[0].startDate
          this.periodStatusChanges[2] = !moment(preStart).isSame(value)
        }
      } else if (str === 'nodeEndDate') {
        if (this.nodeStartDate && value) {
          const dates = await this.getAll(moment(this.nodeStartDate).format('YYYY-MM-DD'), moment(value).format('YYYY-MM-DD'))
          const preEnd = this.detailInfo.proNodeList.filter(item => item.proNodeId === this.periodId)[0].endDate
          this.generateColumns(dates)
          this.periodStatusChanges[3] = !moment(preEnd).isSame(value)
        }
      } else if (str === 'proStartDate' || str === 'proEndDate') {
        this.$message({
          message: '请修改节点周期',
        })
        const preStart = this.detailInfo.proStartDay
        const preEnd = this.detailInfo.proEndday
        this.periodStatusChanges[0] = str === 'proStartDate' ? !moment(preStart).isSame(value) : false
        this.periodStatusChanges[1] = str === 'proEndDate' ? !moment(preEnd).isSame(value) : false
      } else if (str === 'endDate') {
        const currentItem = this.dataSource[index]
        const start = this.dataSource[index].inputStart
        const flag = value && moment(value).isBefore(start)
        const isBetweenNodeDate = this.nodeStartDate && this.nodeEndDate && value && moment(value).isBetween(this.nodeStartDate, this.nodeEndDate, null, '[]')
        if (!currentItem.hasOwnProperty('isAdd')) {
          const preDate = this.initDataSource[0].inputEnd
          this.dataSource[index].changesArr[2] = !moment(value).isSame(preDate)
        }
        if (!isBetweenNodeDate) {
          this.$message('选择日期不在节点范围')
          this.dataSource[index].inputEnd = ''
        } else if (flag) {
          this.$message('请选择大于开始时间的日期')
          this.dataSource[index].inputEnd = ''
        } else {
          if (currentItem.inputType == 2) {
            this.reCalcData(index)
          } else {
            this.reCalcCustomerData(index)
          }
        }
      } else if (str === 'startDate') {
        const currentItem = this.dataSource[index]
        // if (!currentItem.hasOwnProperty('isAdd')) {
        //   const preDate = this.initDataSource[0].inputStart
        //   this.dataSource[index].changesArr[1] = !moment(value).isSame(preDate)
        // }
        // if (currentItem.inputType == 2) {
        //   this.reCalcData(index)
        // } else {
        //   this.reCalcCustomerData(index)
        // }
      }
      if (str === 'nodeStartDate' || str === 'nodeEndDate' || str === 'proStartDate' || str === 'proEndDate') {
        let arr = this.deepClone(this.dataSource)
        arr.map(el => {
          if (!el.inputStart || !el.inputEnd) {
            this.columns.forEach(item => {
              el.inputHours = ''
              el[item.label] = ''
            })
          }
        })
        this.dataSource = arr
      }
    },
    /***
     * isToggle是否是切换
     **/
    async generateColumns(dates, flag, isToggle) {
      const result = []
      const timeStamp = (new Date()).getTime()
      dates.map((item, index) => result.push({
        label: item,
        prop: '',
        id: timeStamp + index
      }))
      const dataSource = this.deepClone(this.dataSource)
      dataSource.map((item, index) => {
        if (flag) {
          dates.map(el => {
            const arr = item.planHoursList.filter(curr => curr.planDate == el)
            item[`${el}`] = (arr && arr.length && arr[0].inputHours) || ''
          })
        } else {
          const excludeDates = []
          if (isToggle == false || isToggle == true) {
            this.workDays.filter(el => {
              const isexclude = moment(el.date).isBetween(item.inputStart, item.inputEnd, null, '[]')
              if (!isexclude || (isToggle && !el.isValid)) {
                excludeDates.push(el)
              }
            })
          }
          dates.map(el => item[`${el.date}`] = dataSource[index][`${el.date}`] || '')
          excludeDates.map(el => item[`${el.date}`] = '')
        }
        item.changesArr = [false, false, false, false]
        if (item.inputStart) {
          item.inputStart = moment(item.inputStart).format('YYYY-MM-DD')
        }
        if (item.inputEnd) {
          item.inputEnd = moment(item.inputEnd).format('YYYY-MM-DD')
        }
        if (item.inputType ==  1){
            item.inputHours = dates.reduce((pre, curr) => pre += Number(item[curr]? item[curr] : 0), 0)
        } else {
          if (isToggle == true) {
            const limitArr = this.workDays.filter(el => moment(el.date).isBetween(item.inputStart, item.inputEnd, null, '[]') && el.isValid) || []
            limitArr.map(element => item[element.date] = (item.inputHours / limitArr.length).toFixed(2))
          } else if (isToggle == false) {
            const limitArr = this.workDays.filter(el => moment(el.date).isBetween(item.inputStart, item.inputEnd, null, '[]')) || []
            limitArr.map(element => item[element.date] = (item.inputHours / limitArr.length).toFixed(2))
          }
        }
      })
      this.columns = result
      this.dataSource = dataSource
    },
    deepClone(target) {
      let result
      if (typeof target === 'object') {
        if (Array.isArray(target)) {
          result = []
          for (const i in target) {
            result.push(this.deepClone(target[i]))
          }
        } else if (target === null) {
          result = null
        } else if (target.constructor === RegExp) {
          result = target
        } else {
          result = {}
          for (const i in target) {
            result[i] = this.deepClone(target[i])
          }
        }
      } else {
        result = target
      }
      return result
    },
    inputChanges(value, record, index, date) {
      if (record.inputType == 1) {
        this.calcTotal(index, true)
        const isBetweenDates = moment(date).isBetween(record.inputStart, record.inputEnd, null, '[]')
        if (record.inputStart && record.inputEnd && !isBetweenDates) {
          this.$message('当前日期不在开始和结束日期之间')
        }
      } else {
        this.reCalcCustomerData(index)
      }
    },
    // 累计投入是否发生变更
    inputTotalChanges(value, scope) {
      const index = scope.$index
      // const flag = this.checkTotalIsLegal(value, index)
      // if (!flag) return
      if (!scope.row.hasOwnProperty('isAdd')) {
        const preTotal = this.initDataSource[index].inputHours
        this.dataSource[index].changesArr[3] = preTotal != value
      }
      if (scope.row.inputType == 2) {
        this.reCalcData(index)
      }
    },
    checkTotalIsLegal(value, index) {
      const item = this.dataSource[index]
      const startDate = moment(item.inputStart).format('YYYY-MM-DD')
      const endDate = moment(item.inputEnd).format('YYYY-MM-DD')
      const limitArr = this.workDays.filter(el => moment(el.date).isBetween(startDate, endDate, null, '[]') && el.isValid) || []
      const arr = !this.isLimit ? (this.workDays.filter(el => moment(el.date).isBetween(startDate, endDate, null, '[]')) || []) : (limitArr || [])
      const beforeDateList = arr.filter(el => moment(el.date).isBefore(this.serverDate))
      const beforeTotal = beforeDateList.reduce((pre, el) => pre += (Number(item[el.date] || 0)), 0)
      const preTotal = arr.reduce((pre, el) => pre += (Number(item[el.date] || 0)), 0)
      if (value < beforeTotal) {
        this.$message(`累计投入不能小于${beforeTotal}`)
        item.inputHours = preTotal
        return false
      }
      return true
    },
    reset() {
      this.setDefaultValue()
    },
    selectChanges(value, scope) {
      const index = scope.$index
      if (!scope.row.hasOwnProperty('isAdd')) {
        const item = this.dataSource[index]
          // console.log("item",item)
        const inputType = item.inputType
        this.dataSource[index].changesArr[0] = inputType != value
      }
      if (value == 1) { // 自定义
        this.calcTotal(index,true)
      } else { // 平均
        this.reCalcData(index)
      }
    },
    // 重新计算
    reCalcData(index) {
      const item = this.dataSource[index]
      if (item.inputStart && item.inputEnd) {
        const startDate = moment(item.inputStart).format('YYYY-MM-DD')
        const endDate = moment(item.inputEnd).format('YYYY-MM-DD')
        const limitArr = this.workDays.filter(el => moment(el.date).isBetween(startDate, endDate, null, '[]') && el.isValid) || []
        const arr = !this.isLimit ? (this.workDays.filter(el => moment(el.date).isBetween(startDate, endDate, null, '[]')) || []) : (limitArr || [])
        const rest = this.columns.filter(el => !arr.some(element => element.date == el.label))
        if (item.inputHours) { // 存在累计投入
          arr.map(el => {
            const result = item.inputHours / (arr.length)
            item[`${el.date}`] = result && result.toFixed(2)
          })
        } else { // 不存在累计投入
          item.inputHours = 0
          arr.map(el => item[`${el.date}`] = 0)
        }
        rest.map(el => item[`${el.label}`] = '')
      }
    },
    // 自定义日期更改重新计算
    reCalcCustomerData(index) {
      const item = this.dataSource[index]
      if (item.inputStart && item.inputEnd) {
        const startDate = moment(item.inputStart).format('YYYY-MM-DD')
        const endDate = moment(item.inputEnd).format('YYYY-MM-DD')
        const limitArr = this.workDays.filter(el => moment(el.date).isBetween(startDate, endDate, null, '[]')).map(itemA => itemA.isValid) || []
        const arr = !this.isLimit ? (this.workDays.filter(el => moment(el.date).isBetween(startDate, endDate, null, '[]')) || []) : (limitArr || [])
        const rest = this.columns.filter(el => !arr.some(element => element.date == el.label))
        rest.map(el => item[`${el.label}`] = '')
        item.inputHours = arr.reduce((total, curr) => total += Number((item[`${curr.date}`] || 0)), 0)
      }
    },
    closeDialog(item, index) {
      const isRepate = this.dataSource.some(el => el.userId == item.userId)
      if (isRepate) {
        this.$message('该职员已添加')
        return
      }
      const user = {
        isAdd: true, // 标识当前用户数据是通过新增来的
        ...item,
        inputStart: '',
        inputEnd: '',
        nodeId: this.periodId,
        inputType: 2,
        proroleName: item.roleName,
        inputHours: ''
      }
      this.columns.map(el => user[`${el.label}`] = '')
      this.dataSource.push(user)


    },
    /**
     * 计算累计投入
     * index: 当前dataSource的index
     */
    calcTotal(index, flag) {
      if (flag) {
        const item = this.dataSource[index]
        item.inputHours = this.columns.reduce((pre, curr) => pre += (Number(item[`${curr.label}`]) || 0), 0)
      } else {
        this.dataSource.map(item => item.inputHours = this.columns.reduce((pre, curr) => pre += parseInt((item[`${curr.label}`] || 0), 10), 0))
      }
    },
    async toggleLimit(value) {
      if (!value) {
        const dates = this.workDays.map(el => el.date)
        await this.generateColumns(dates, false, false)
      } else {
        const dates = this.workDays.filter(item => item.isValid).map(el => el.date)
        await this.generateColumns(dates, false, true)
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    async saveData() {
      const res = await this.enterUsed()
      if (res) {
        this.periodId = this.currentClickNodeId
        sessionStorage.setItem('changesItem', this.currentClickNodeId)
        this.$nextTick(() => {
          this.setDefaultValue()
        })
      }
      this.dialogVisible = false
    },
    enterDetail() {
      this.$router.push({
        path: '/change/detail',
        query: {
          id: this.id,
          proNodeId: this.periodId
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
$baseLeftWidth: 40px;
.wrapper{
  padding: 40px;
  .list{
    display: flex;
    flex-direction: column;
    padding: 10px;
    .item{
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      margin-bottom: 30px;
      &_title{
        width: 100px;
        display: flex;
        align-self: center;
        text-align: right;
        white-space: nowrap;
        flex: none;
        flex-direction: row;
        justify-content:flex-end;
        .required{
        float: left;
        &:after{
          content: "*";
          margin-right: 3px;
          color: red;
          height: 10px;
        }
      }
      }
      .item_summary{
        align-self: flex-start;
      }
      .node_wrapper{
        width: 100%;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        .nodes{
          margin-left: $baseLeftWidth;
          display: flex;
          flex-direction: row;
          flex-wrap: nowrap;
          font-size: 14px;
          // .btn{
          //   border-right: 0px;
          //   border-top-right-radius: 0;
          //   border-bottom-right-radius: 0px;
          //   // position: relative;
          //   &::after{
          //     content: '';
          //     width: 0;
          //     height: 0;
          //     border-top: 10px solid transparent;
          //     border-left: 10px solid red;
          //     border-bottom: 10px solid transparent;
          //     position: relative;
          //     // border: 20px solid #d8d8d8;
          //     // border-color: #d8d8d8 transparent transparent;
          //     // width: 0;
          //     // height: 0;
          //     top:  50%;
          //     left: 10px;
          //     transform: translateY(-50%) scale(180edg);
          //   }
          // }
          // .container{
          //   font-size: 14px;
          //   height: 28px;
          //   display: -webkit-box;
          //   display: -ms-flexbox;
          //   display: flex;
          //   -webkit-box-align: center;
          //   -ms-flex-align: center;
          //   align-items: center;
          //   -webkit-box-pack: center;
          //   -ms-flex-pack: center;
          //   justify-content: center;
          //   position: relative;
          //   margin-right: 15px;
          //   padding: 0 5px 0 5px;
          //   border: 1px solid black;
          //   border-radius: 1px;
          //   background: #ffffff;
          //   cursor: pointer;
          //   &::after{
          //     content: "";
          //     border: 14px solid #ffffff;
          //     border-top-color: transparent;
          //     border-right-color: transparent;
          //     border-bottom-color: transparent;
          //     width: 0px;
          //     height: 0px;
          //     position: absolute;
          //     right: -28px;
          //   }
          //   &::before{
          //     content: "";
          //     border: 14px solid black;
          //     border-top-color: transparent;
          //     border-right-color: transparent;
          //     border-bottom-color: transparent;
          //     width: 0px;
          //     height: 0px;
          //     position: absolute;
          //     right: -29px;
          //   }
          //   &_active{
          //     background: #d7d7d7;
          //     &::after{
          //       border-left: 14px solid #d7d7d7;
          //     }
          //   }
          // }
        }
        .changes{
          text-decoration: underline;
        }
      }
      .time, .summary{
        margin-left: $baseLeftWidth;
      }

      .summary{
        width: 456px;
      }
      // .required{
      //   position: relative;
      //   &:after{
      //     content: "*";
      //     position: absolute;
      //     top: 2px;
      //     left: -11px;
      //     color: red;
      //     height: 10px;
      //   }
      // }
      .datePicker{
        width: 140px;
      }
      .time_table{
        overflow: auto;
        .addUser{
          margin-top: 10px;
        }
        .workhour{
          ::v-deep .el-input__inner{
            padding: 0 0 0 15px;
          }
        }
      }
    }
    .item_checkbox{
      display: flex;
      flex-direction: row;
      justify-content: flex-end;
      margin-bottom: 20px;
    }
  }
  .operation{
    margin: 20px 0 100px 300px;
    .tips{
      position: relative;
      &::after{
        position: absolute;
        content: '当前节点变更正在审批中，不可修改';
        color: red;
        top: 60px;
        left: 50%;
        transform: translateX(-50%)
      }
    }
    .tips2{
      position: relative;
      &::after{
        position: absolute;
        content: '当前节点已过期,不可变更';
        color: red;
        top: 60px;
        left: 50%;
        transform: translateX(-50%)
      }
    }
    .tips3{
      position: relative;
      &::after{
        position: absolute;
        content: '当前节点未分配,不可变更';
        color: red;
        top: 60px;
        left: 50%;
        transform: translateX(-50%)
      }
    }
      .tips4{
          position: relative;
          &::after{
              position: absolute;
              content: '当前节点已过期,无法提交变更';
              color: red;
              top: 60px;
              left: 50%;
              transform: translateX(-50%)
          }
      }
  }
}
</style>
<style lang="less" scoped>
    .el-button{
        /deep/ span{
            margin-left: 0px;
        }
    }
    /deep/.cell{
        .el-date-editor{
            /deep/.el-input__inner{
                padding-left: 30px;
                padding-right: 0px;
            }
        }
    }
</style>
